package com.itheima.tliaswebmanagement.interceptor;

import com.itheima.tliaswebmanagement.utils.JwtUtils;
import com.itheima.tliaswebmanagement.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description LoginCheckInterceptor
 * @Author ziguan ling
 * @Date 2025--01--11
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token == null || token.equals("")){
            response.setStatus(401);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            log.info("员工id：{}登录校验成功了", id);
            ThreadLocalUtil.setLoginId((Integer)id);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

        return  true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex){
     ThreadLocalUtil.removeLogin();
    }
}
